<?php
	//create messages
	function mk_create_message($user_id, $subject, $body, $parties)
  {
  
    global $mngl_message, $mngl_user ,$mngl_messages_controller;
    
    $ids = array();
    $screennames = $parties;
    
    if(is_array($screennames))
    {
      foreach($screennames as $screenname)
      {
        $curr_user =& MnglUser::get_stored_profile_by_screenname($screenname);
        
        if($curr_user and is_object($curr_user))
          $ids[] = $curr_user->id;
      }
  
      $ids[] = $user_id;
      $ids = array_unique($ids); // Remove any duplicates
    }

    $errors = $mngl_message->validate($_POST, $ids, array());

	unset($errors);
		
    if(empty($errors))
    {
      if($mngl_messages_controller->send_initial_message( $mngl_user->id, $ids, $subject, $body ))
        require( MNGL_VIEWS_PATH . "/mngl-messages/message_sent.php" );
      // $mngl_messages_controller->display_messages(1,true);
    }
    else
    {
      require( MNGL_VIEWS_PATH . "/shared/errors.php" );
      // $mngl_messages_controller->display_messages();
	  
    }
  }
  
	//find friends
	function mk_lookup_friends($output='json')
  {
    global $mngl_user, $mngl_friend, $mngl_utils, $mngl_message;

    if($output=='json')
    {
      if ($mngl_user->is_admin()) //Allows admins to message all users regardless of friendship status
        $friends_array = $mngl_message->get_all_users_if_admin("user_login <> '{$mngl_user->screenname}'");
      else
        $friends_array = $mngl_friend->get_all_by_user_id( $mngl_user->id, "status='verified' " );
      $fmt_friends_array = array();
      foreach($friends_array as $friend)
      {
        $avatar = get_avatar($friend->ID, 20);
        $screenname = $friend->user_login;
        $higlighted_screenname = $screenname;
        
        $fmt_friends_array[] = array("id" => $friend->ID, "value" => $screenname, "label" => "<span class='mngl_friend_dropdown_item'>{$avatar}&nbsp;<span class='mngl_friend_dropdown_text'>{$higlighted_screenname}</span></span>");
      }
      return $fmt_friends_array;
    }
  }

  if(!empty($_POST['mk_sent_message'])){
	if($_POST['mk_sent_message'] == 'mngl_mk_process_composer_form'){
		$user_id = $_POST['mngl_user_id'];
		$subject = $_POST['mngl_message_subject'];
		$body = $_POST['mngl_message_body'];
		$parties = $_POST['mngl_mk_message_recipients'];
		mk_create_message($user_id, $subject, $body, $parties);
		
	}
  }
  
  
	$friends  = mk_lookup_friends() ;

?>
<div id="mngl_dk_message_composer" class="mngl_gray_box">
<form action="" enctype="multipart/form-data" method="post" autocomplete="off">
  <input type="hidden" name="mk_sent_message" id="mk_sent_message" value="mngl_mk_process_composer_form" />
  <input type="hidden" name="<?php echo $mngl_user->id_str; ?>" id="<?php echo $mngl_user->id_str; ?>" value="<?php echo $mngl_user->id; ?>" />
  <input type="hidden" name="<?php echo $mngl_user->screenname_str; ?>" id="<?php echo $mngl_user->screenname_str; ?>" value="<?php echo $mngl_user->screenname; ?>" />
  <table width="100%" class="profile-edit-table">

  
	<tr>
      <td valign="top" width="100px"><?php _e('Select Friends', 'mingle'); ?>:</td>
	  
      <td valign="top">
	  <div id="dk_group_friends">
				<?php
					foreach($friends as $friend){
						echo '<div>';
						echo '<INPUT name="mngl_mk_message_recipients[]" type="checkbox" value="'.$friend["value"].'" /> ';
						echo $friend['label'];
						echo '</div> ';
					}
					
					print_r($_POST['mngl_message_recipients']);
				?>
		</div>
      </td>
    </tr>
	
	
    <tr>
      <td valign="top"><?php _e('Subject', 'mingle'); ?>:</td>
      <td valign="top"><input type="input" name="mngl_message_subject" id="mngl_message_subject" value="<?php echo MnglAppHelper::format_text($_POST['mngl_message_subject']); ?>" class="mngl-profile-edit-field" /></td>
    </tr>
    <tr>
      <td valign="top"><?php _e('Message', 'mingle'); ?>:</td>
      <td valign="top"><textarea name="mngl_message_body" id="mngl_message_body" class="mngl-profile-edit-field mngl-growable"><?php echo MnglAppHelper::format_text($_POST['mngl_message_body']); ?></textarea></td>
    </tr>
  </table>
  <input type="submit" class="mngl-share-button" name="Update" value="<?php _e('Send', 'mingle'); ?>" />
</form>
</div>

<script type="text/javascript">
jQuery(function() {
	function split(val) {
		return val.split(/,\s*/);
	}

	function extractLast(term) {
		return split(term).pop();
	}
	
	jQuery("#mngl_message_recipients").autocomplete({
		source: function(request, response) {
			jQuery.getJSON("<?php echo MNGL_SCRIPT_URL . "&controller=messages&action=lookup_friends"; ?>", {
				sq: extractLast(request.term)
			}, response);
		},
		search: function() {
			// custom minLength
			var term = extractLast(this.value);
			if (term.length < 2) {
				return false;
			}
		},
		focus: function() {
			// prevent value inserted on focus
			return false;
		},
		select: function(event, ui) {
			var terms = split( this.value );
			// remove the current input
			terms.pop();
			// add the selected item
			terms.push( ui.item.value );
			// add placeholder to get the comma-and-space at the end
			terms.push("");
			this.value = terms.join(", ");
			return false;
		}
	});
	
	<?php echo (((isset($_POST['action']) and ($_POST['action'] == 'mngl_process_composer_form')) or (isset($_GET['mu']) and !empty($_GET['mu'])))?'':"jQuery('#mngl_dk_message_composer').hide();"); ?>
});
</script>
